<template>
  <div>
    <div class="boxWrapper tabbox">
        <el-tabs v-model="currentName" @tab-click="handleChangeTab">
            <el-tab-pane label="电站列表" name="1">
                    <span slot="label"><i class="iconfont">&#xe621;</i> 电站列表</span>
            </el-tab-pane>
            <el-tab-pane label="采集列表" name="2">
                    <span slot="label"><i class="iconfont">&#xe657;</i> 采集列表</span>
            </el-tab-pane>
            <el-tab-pane label="采集设置" name="3">
                    <span slot="label"><i class="iconfont">&#xe644;</i> 采集设置</span>
            </el-tab-pane>
        </el-tabs>
    </div>    
    <div class="collection-management boxWrapper" v-if="currentName == '1'">
        <el-form :inline="true">
            <el-form-item label="流域">
                <el-select 
                    v-model="basinId" 
                    placeholder="选择流域" 
                    size="medium" 
                    @change="handleChangeBasin"
                    class="basin-select"
                    >
                    <el-option
                        v-for="item in basinSelect"
                        :key="item.id"
                        :label="item.basinName"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>  
        </el-form>
        <div class="station-cards-container" style="margin-top:-20px">
        <el-row :gutter="16">
            <el-col 
            :xs="24" :sm="12" :md="8" :lg="6" 
            v-for="station in stationData" 
            :key="station.stationId"
            >
            <el-card class="station-card" shadow="hover">
                <div class="card-header">
                <h3 class="station-name">{{ station.stationName }}</h3>
                <el-tag 
                    :type="station.onlineNum > 0 ? 'success' : 'info'" 
                    size="small"
                >
                    {{ station.onlineNum > 0 ? '运行中' : '无设备在线' }}
                </el-tag>
                </div>
                
                <div class="status-info">
                <div class="status-item">
                    <span class="label">绑定状态:</span>
                    <el-button 
                    :type="station.bindNum == 0 ? 'warning' : 'primary'" 
                    size="mini" 
                    @click="station.bindNum == 0 ? handleBind(station) : handleBindingList(station)"
                    plain
                    >
                    {{ station.bindNum == 0 ? '立即绑定' : `已绑定(${station.bindNum})` }}
                    </el-button>
                </div>
                
                <div class="status-item">
                    <span class="label">设备状态:</span>
                    <div class="device-status">
                    <span class="online-count">
                        <i class="el-icon-success status-icon online"></i>
                        在线({{ station.onlineNum }})
                    </span>
                    <span class="offline-count">
                        <i class="el-icon-error status-icon offline"></i>
                        离线({{ station.offlineNum }})
                    </span>
                    </div>
                </div>
                
                <div class="status-item">
                    <span class="label">采集间隔:</span>
                    <div class="interval-control">
                    <el-input-number 
                        v-model="station.collectionInterval" 
                        :min="0" 
                        size="mini" 
                        @change="handleSetTask(station)"
                        controls-position="right"
                    ></el-input-number>
                    <span class="unit">秒</span>
                    </div>
                </div>
                </div>
                
                <div class="card-actions">
                <el-button 
                    icon="el-icon-setting" 
                    size="mini" 
                    @click="handleBindingList(station)"
                >
                    绑定管理
                </el-button>
                </div>
            </el-card>
            </el-col>
        </el-row>
        </div>
   </div> 

    <div class="collection-management boxWrapper" v-if="currentName == '2'">
        <el-form :inline="true">
            <el-form-item label="流域">
                <el-select v-model="basinIdRecord" placeholder="请选择" size="small" @change="handleChangeBasinRecord">
                <el-option
                    v-for="item in basinSelect"
                    :key="item.id"
                    :label="item.basinName"
                    :value="item.id"
                    >
                </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="电站">
                <el-select v-model="stationRecord" placeholder="请选择" size="small" @change="handleChangeStationRecord" style="margin-left:20px">
                <el-option
                    v-for="item in stationSelect"
                    :key="item.id"
                    :label="item.stationName"
                    :value="item.id"
                    >
                </el-option>
                </el-select>
            </el-form-item>    
        </el-form>

        <el-table :data="tableList" height="calc(100vh - 280px)" border ref="uploadTableRef">
            <el-table-column prop="stationName" label="电站" align="center"></el-table-column>
            <el-table-column prop="startTime" label="开始时间" align="center"></el-table-column>
            <el-table-column prop="endTime" label="结束时间" align="center"></el-table-column>
            <el-table-column prop="pointNumCollect" label="采集测点（个）" align="center">
            </el-table-column>
            <el-table-column prop="collectDataNum" label="采集数量（条）" align="center">
            </el-table-column>
            <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
                <el-tag type="info" size="small" v-if="scope.row.status == 0">未开始</el-tag>
                <el-tag type="primary" size="small" v-if="scope.row.status == 1">进行中</el-tag>
                <el-tag type="success" size="small" v-if="scope.row.status == 2">已结束</el-tag>
            </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="采集结果" align="center">
            <template slot-scope="scope">
                <el-tag type="info" size="small" v-if="scope.row.result == 0">未知 {{scope.row.extMsg}}</el-tag>
                <el-tag type="danger" size="small" v-if="scope.row.result == 1">失败 {{scope.row.extMsg}}</el-tag>
                <el-tag type="success" size="small" v-if="scope.row.result == 2">成功</el-tag>
            </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
            <template slot-scope="scope">
                <el-button type="text" icon="el-icon-tickets" @click="handleTaskDetail(scope.row)">测点采集记录</el-button>
                <el-button type="text" v-if="scope.row.clientOnline != 1 && scope.row.clientOnline != 0" icon="el-icon-download" @click="handleTaskLog(scope.row)">采集日志</el-button>
            </template>
            </el-table-column>
        </el-table>
    </div>

    <div class="collection-management3 boxWrapper" v-if="currentName == '3'">
        <div class="config-container">
            <el-card class="config-card" shadow="never">
            <div slot="header" class="card-header">
                <span class="header-title">采集策略配置</span>
                <span class="header-desc">设置系统级的采集参数和策略</span>
            </div>
            
            <el-form :model="formData" size="medium" label-width="180px" class="config-form">
                <el-form-item label="服务端采集并行数" class="form-item-custom">
                <el-input-number 
                    v-model="formData.serverParallelNum" 
                    :min="1" 
                    :max="50"
                    controls-position="right"
                    class="custom-input-number"
                ></el-input-number>
                <div class="form-tip">
                    <i class="el-icon-info tip-icon"></i>
                    <span>限制同一时间段允许并行采集的电站数量</span>
                </div>
                </el-form-item>
                
                <el-form-item label="采集间隔(秒)" class="form-item-custom">
                <el-input-number 
                    v-model="formData.collectInterval" 
                    :min="5" 
                    :max="3600"
                    controls-position="right"
                    class="custom-input-number"
                ></el-input-number>
                <div class="form-tip">
                    <i class="el-icon-info tip-icon"></i>
                    <span>如未对电站进行单独设置采集间隔，则默认使用此策略</span>
                </div>
                </el-form-item>
            </el-form>
            
            <div class="action-buttons">
                <el-button 
                type="primary" 
                icon="el-icon-check" 
                @click="handleSaveTask"
                class="save-btn"
                size="small"
                >
                保存配置
                </el-button>
            </div>
            </el-card>
        </div>
    </div>

    <!-- 对话框 -->
    <el-dialog 
      :title="`绑定客户端 - ${currentStation ? currentStation.stationName : ''}`" 
      :visible.sync="unbindingDialogVisible" 
      width="900px"
    >
      <el-table 
        :data="unbindingList" 
        height="400px" 
        border 
        highlight-current-row 
        @current-change="handleCurrentChange"
        style="width: 100%"
      >
        <el-table-column prop="name" label="自定义备注" align="center" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.name" placeholder="请输入内容" size="small" v-if="scope.row.showInput"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="onlineStatus" label="状态" align="center" width="80">
          <template slot-scope="scope">
            <el-tag  type="danger" size="small" v-if="scope.row.onlineStatus == 0">离线</el-tag> 
            <el-tag type="success" size="small" v-if="scope.row.onlineStatus == 1">在线</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="wanIp" label="公网IP" align="center" width="120"></el-table-column>
        <el-table-column prop="lanIp" label="内网IP" align="center" width="120"></el-table-column>
        <el-table-column prop="clientId" label="客户端ID" align="center"></el-table-column>
      </el-table>
      
      <div class="dialog-footer">
            <el-button @click="handleCancelUnBinding" size="small" icon="el-icon-close" class="cancel-btn">取消</el-button>
            <el-tooltip class="item" effect="dark" content="请点击表格选择要绑定的电站" placement="top-start" :disabled="selectedClient !== null">
                    <el-button 
                    type="primary" 
                    size="small"
                    @click="handleConfirmUnBinding" 
                    :disabled="selectedClient == null"
                    icon="el-icon-check"
                    class="confirm-btn"
                    >
                    确认绑定
                    </el-button>
            </el-tooltip>
      </div>
    </el-dialog>

    <el-dialog 
      :title="`已绑定客户端 - ${currentStation ? currentStation.stationName : ''}`"  :visible.sync="bindingDialogVisible"  width="80%">
      <el-table :data="bindingList" height="400px" border>
        <el-table-column prop="name" label="备注" align="center" ></el-table-column>
        <el-table-column prop="onlineStatus" label="状态" align="center" >
          <template slot-scope="scope">
            <el-tag  type="danger" size="small" v-if="scope.row.onlineStatus == 0">离线</el-tag> 
            <el-tag type="success" size="small" v-if="scope.row.onlineStatus == 1">在线</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bindTime" label="绑定时间" align="center" ></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" ></el-table-column>
        <el-table-column prop="wanIp" label="公网IP" align="center" ></el-table-column>
        <el-table-column prop="lanIp" label="内网IP" align="center" w></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button 
              type="danger" 
              icon="el-icon-connection" 
              size="mini" 
              @click="handleDelBind(scope.row)"
              plain
            >
              解绑
            </el-button>
            <el-button 
              type="primary" 
              icon="el-icon-tickets" 
              size="mini" 
              @click="handleOnLineList(scope.row)"
              plain
              style="margin-top: 5px;"
            >
              记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog 
      title="客户端上线记录" 
      :visible.sync="onLineDialogVisible" 
      width="60%"
      custom-class="custom-dialog"
    >
      <el-table :data="onLineList" height="400px" border>
        <el-table-column prop="etime" label="时间" align="center"></el-table-column>
        <el-table-column prop="content" label="记录" align="center"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="记录详情" :visible.sync="recordDetailVisible" width="90%"  v-dialogDrag>
      <el-table :data="recordListDetail" height="500" border>
        <el-table-column prop="startTime" label="开始时间" align="center" width="160"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" align="center" width="160"></el-table-column>
        <el-table-column prop="codeName" label="测点" align="center" width="160"></el-table-column>
        <el-table-column prop="dataNum" label="采集数量（条）" align="center" width="120">
        </el-table-column>
        <el-table-column prop="extMsg" label="结果" align="center" width="80">
          <template slot-scope="scope">
            <el-tag size="small" type="info" v-if="scope.row.result == 0">未知 {{ scope.row.extMsg }}</el-tag>
            <el-tag size="small" type="danger" v-if="scope.row.result == 1">失败 {{ scope.row.extMsg }}</el-tag>
            <el-tag size="small" type="success" v-if="scope.row.result == 2">成功</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="execSql" label="sql" align="center" show-overflow-tooltip>
        </el-table-column>
      </el-table>
    </el-dialog> 
  </div>
</template>

<script>
import bus from '@/utils/eventBus.js';
import {GetAllBasin,DaStationList,setTaskInterval,UnBindingStationList,DaBinding,DabindingList,DaClientRecord,DaUnbinding,GetStationByBasinID,recordList,settingCollectDetail,settingCollect,taskRecordPointList,taskRecordLog } from '@/api/https'
export default {
    name:'CollectionOverview',
    data() {
        return {
            currentName:'1',
            basinId:'',
            basinSelect:[],
            stationData:[],
            stationId:'',
            unbindingList:[],
            unbindingDialogVisible:false,
            bindingDialogVisible:false,
            bindingList:[],
            onLineDialogVisible:false,
            onLineList:[],
            currentStation: null,
            selectedClient: null,
            tableList:[],
            currentPage:1,
            basinIdRecord:'',
            stationRecord:'',
            formData:{},
            recordDetailVisible:false,
            recordListDetail:[],
        }
    },
    mounted(){
        bus.$emit('showBasin', false);
        window.addEventListener("scroll", this.loadMore, true);
        this.getAllBasin()
    },
    activated(){
        bus.$emit('showBasin', false);
    },
    methods:{
        handleChangeTab(){
            if(this.currentName == '3'){
                settingCollectDetail().then(res=>{
                    if(res.code == 200){
                        this.formData = {...res.data}
                    }
                })
            }
        },
        getAllBasin(){
            GetAllBasin({
                ORGID:0,
            }).then(res=>{
                if(res.isSuccess){
                    this.basinSelect = res.data
                    this.basinId = res.data[0].id
                    this.basinIdRecord = res.data[0].id
                    this.getStationData()
                    this.handleGetStationSelect()
                }
            })
        },
        handleChangeBasin(val){
            this.basinId = val
            this.getStationData()
        },
        getStationData(){
            DaStationList({
                basinId:this.basinId,
                page:1,
                size:50
            }).then(res=>{
                if(res.code == 200){
                    this.stationData = res.data.list || []
                }
            })
        },
        handleSetTask(data){
            setTaskInterval({
                stationId:data.stationId,
                collectionInterval:data.collectionInterval
            }).then(res=>{
                if(res.code == 200){
                    this.$message.success('采集间隔时间设置成功！')
                }else{
                    this.getStationData()
                    this.$message.error(res.msg)
                }
            })
        },
        handleBind(data){
            this.currentStation = data;
            UnBindingStationList({
                stationId:data.stationId
            }).then(res=>{
                if(res.code == 200){
                    const list = []
                    if(res.data && res.data.length > 0){
                        res.data.forEach(item=>{
                            const _d = {...item}
                            _d.showInput = false
                            _d.stationId = data.stationId
                            list.push(_d)
                        })
                    }
                    this.unbindingList = [...list]
                    this.unbindingDialogVisible = true
                }
            })
        },
        handleCancelUnBinding(){
            this.unbindingList = []
            this.currentStation = null
            this.unbindingDialogVisible = false
            this.selectedClient = null
        },
        handleConfirmUnBinding(){
            const selectBindData = this.unbindingList.filter(item=>{return item.showInput})
            if(selectBindData.length > 0 ){
                DaBinding({
                    clientId:selectBindData[0].clientId,
                    stationId:selectBindData[0].stationId,
                    name:selectBindData[0].name || ''
                }).then(res=>{
                    if(res.code == 200){
                        this.handleCancelUnBinding()
                        this.getStationData()
                    }else{
                        this.$message.error(res.msg)
                    }
                })
            }else{
                this.$message.error('请选择要绑定的客户端！')
            }
        },
        handleCurrentChange(data){
            this.selectedClient = data; 
            this.unbindingList.forEach(item=>{
                if(item.clientId == data.clientId){
                    item.showInput = true
                }else{
                    item.showInput = false
                }
            })
        },
        handleBindingList(data){
            this.currentStation = data;
            DabindingList({
                stationId:data.stationId
            }).then(res=>{
                if(res.code == 200){
                    this.bindingList = res.data
                    this.bindingDialogVisible = true
                }else{
                    this.$message.error(res.msg)
                }
            })
        },
        handleOnLineList(data){
            DaClientRecord({
                clientId:data.clientId,
                page:1,
                size:500
            }).then(res=>{
                if(res.code == 200){
                    this.onLineList = res.data.list
                    this.onLineDialogVisible = true
                }
            })
        },
        handleDelBind(data){
            this.$confirm(`确认解除 ${data.name} 的绑定？`,'提示',{
                type:'warning'
            }).then(() => {
                DaUnbinding({
                    clientId:data.clientId
                }).then(res=>{
                    if(res.code == 200){
                        this.getStationData()
                        this.handleBindingList(data)
                    }else{
                        this.$message.error(res.msg)
                    }
                })
            }).catch(() => {}); 
        },
        handleGetStationSelect(){
            GetStationByBasinID(this.basinIdRecord).then(res=>{
                if(res.isSuccess){
                    this.stationSelect = res.data
                    this.stationRecord = res.data[0].id
                    this.currentPage = 1
                    this.tableList = []
                    this.getRecordData()
                }
            })
        },
        handleChangeBasinRecord(val){
            this.basinIdRecord = val
            this.handleGetStationSelect()
        },
        handleChangeStationRecord(val){
            this.stationRecord = val
            this.currentPage = 1
            this.tableList = []
            this.getRecordData()
        },
        getRecordData(){
            recordList({
                page:this.currentPage,
                size:50,
                basinId:this.basinIdRecord,
                stationId:this.stationRecord
            }).then(res=>{
                if(res.code == 200){
                    if(this.tableList.length == 0){
                        this.tableList = res.data.list
                    }else if(this.tableList.length > 0){
                        this.tableList = this.tableList.concat(res.data.list)
                    }
                    this.totalPage =  Math.ceil(res.data.total / 50)
                }
            })
        },
        loadMore(){
            const dom = this.$refs.uploadTableRef?.bodyWrapper
            if (dom?.scrollTop + dom?.clientHeight === dom?.scrollHeight) {
            if (this.currentPage >= this.totalPage) {
                return;
            } else {
                this.currentPage++
                this.getRecordData()
            }
            }
        },
        handleSaveTask(){
            settingCollect(this.formData).then(res=>{
                if(res.code == 200){
                    this.$message.success('设置成功')
                }else{
                    this.$message.error(res.msg)
                }
            })
        },
        handleTaskDetail(data){
            taskRecordPointList({
                page:1,
                size:500,
                id:data.id,
                codeId:''
            }).then(res=>{
                if(res.code == 200){
                    this.recordListDetail = res.data.list
                }else{
                    this.recordListDetail = []
                }
            })
            this.recordDetailVisible = true
        },
        handleTaskLog(data){
            taskRecordLog({
                id:data.id
            }).then(res=>{
                if(res.code == 200){
                    window.location.href = res.data
                }else{
                    this.$message.error(res.msg)
                }
            })
        },
    }
}
</script>

<style scoped lang="scss">
.collection-management {
  height: calc(100vh - 190px);
  padding:20px;
  background: rgba(255,255,255,.8);
  margin-top: 10px;
  box-sizing: border-box;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.page-title {
  color: #303133;
  font-weight: 500;
  margin: 0;
}

.basin-select {
  width: 200px;
  margin-bottom: 20px;
  margin-left:10px;
}

.station-cards-container {
  padding: 0 10px;
}

.station-card {
  margin-bottom: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.station-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12) !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
}

.station-name {
  margin: 0;
  font-size: 16px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 70%;
}

.status-info {
  margin-bottom: 15px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.status-item .label {
  color: #606266;
  font-size: 13px;
}

.device-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.online-count, .offline-count {
  font-size: 12px;
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.online {
  color: #67c23a;
}

.offline {
  color: #f56c6c;
}

.status-icon {
  margin-right: 4px;
  font-size: 14px;
}

.interval-control {
  display: flex;
  align-items: center;
}

.interval-control >>> .el-input-number {
  width: 100px;
}

.unit {
  margin-left: 6px;
  font-size: 12px;
  color: #909399;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
}

.card-actions .el-button {
  margin-left: 8px;
}


.collection-management3 {
  height: calc(100vh - 190px);
  padding:20px;
  background: rgba(255,255,255,.8);
  margin-top: 10px;
  box-sizing: border-box;
  .config-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100%;
}

.config-card {
  border-radius: 8px;
  border: 1px solid #e6ebf5;
}

.card-header {
  display: flex;
  flex-direction: column;
  padding: 0;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.header-desc {
  font-size: 12px;
  color: #909399;
}

.config-form {
  padding: 20px 30px;
}

.form-item-custom {
  margin-bottom: 28px;
  padding: 12px 0;
  border-bottom: 1px dashed #ebeef5;
}

.form-item-custom:last-child {
  border-bottom: none;
  margin-bottom: 20px;
}

::v-deep .form-item-custom .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.custom-input-number {
  width: 200px;
}

.form-tip {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.tip-icon {
  color: #409EFF;
  margin-right: 6px;
}

.form-tip span {
  font-size: 12px;
  color: #606266;
}

.action-buttons {
  text-align: center;
  padding: 20px 0 10px;
  border-top: 1px solid #ebeef5;
  margin: 0 30px;
}

.save-btn {
  padding: 10px 24px;
  border-radius: 4px;
}
}



</style>